<?php

namespace polymerize\order\module\pay;

use app\common\InstanceTrait;
use app\model\VipOrder;
use app\service\AlipayService;
use app\service\WechatService;
use Exception;
use polymerize\order\service\PayModelService;

class PayOrderQuery
{
    use InstanceTrait;

    /**
     * 订单支付结果查询
     *
     * @param string $orderNo
     * @param int    $payType
     * @return array
     * @throws Exception
     */
    public function payOrderQuery(string $orderNo, int $payType): array
    {
        $orderNo = getFilterStr($orderNo);

        $where[]   = ['order_no', '=', $orderNo];
        $where[]   = ['pay_type', '=', $payType];
        $orderInfo = VipOrder::getOne($where);
        if (!$orderInfo) return ['code' => 400, 'msg' => '订单不存在'];
        if ($orderInfo['status'] == 1) return ['code' => 200, 'msg' => '已支付', 'data' => ['pay_status' => 1]];
        $uid = $orderInfo['uid'];

        //支付类型：1=支付宝支付，2=微信支付，3=苹果支付，99=管理员添加
        if ($payType == 1) {
            $query = AlipayService::instance()->_query($orderNo);
            if (is_array($query) && isset($query['alipay_trade_query_response']['trade_status'])) {
                if ($query['alipay_trade_query_response']['trade_status'] == 'TRADE_SUCCESS') {
                    $payTime = isset($query['alipay_trade_query_response']['send_pay_date']) ? $query['alipay_trade_query_response']['send_pay_date'] : myDate();
                    $tradeNo = $query['alipay_trade_query_response']['trade_no'];
                    //更新用户会员表
                    $res = PayModelService::instance()->updateModelByPaySuccess($orderNo, $uid, $orderInfo['vip_type'], $orderInfo['day'], $payTime, $tradeNo);
                    return $res['code'] == 200 ? ['code' => 200, 'msg' => '支付成功', 'data' => ['pay_status' => 1]] : $res;
                }
            }
        }

        if ($payType == 2) {
            $query = WechatService::instance()->_query($orderNo);
            if (is_array($query) && isset($query['trade_state'])) {
                if ($query['trade_state'] == 'SUCCESS') {
                    //"2022-05-24T19:33:40+08:00" to "2022-05-24 19:33:40"
                    $payTime = getBeforeString(str_replace(array('T', 'Z'), ' ', $query['success_time']), '+');
                    $tradeNo = $query['transaction_id'];
                    //更新用户会员表
                    $res = PayModelService::instance()->updateModelByPaySuccess($orderNo, $uid, $orderInfo['vip_type'], $orderInfo['day'], $payTime, $tradeNo);
                    return $res['code'] == 200 ? ['code' => 200, 'msg' => '支付成功', 'data' => ['pay_status' => 1]] : $res;
                }
            }
        }

        return ['code' => 400, 'msg' => '支付失败'];
    }

}

